/**
 * Created by TomSean on 2017/7/24.
 */
var MonthRentPayMent = function ($parent) {
	this.$parent = $parent;
	this.sysUtils = new kendoUtils();
	this.init();
	return this;
}
MonthRentPayMent.prototype = {
	init : function () {
		var $this = this;
		var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find('.search-panel'));
		var functionArray = [
			{fName : 'find_data', fs : this.findReport},
			{fName : 'export_excel', fs : this.exportExcel},
			{fName : 'reset', fs : this.resetInfo}
		];
		this.models = new bindBaseModel(null, fieldArray, functionArray, null);
		this.sysUtils.bindDoucment(this.models, this.$parent, this);
		var selectGroup = this.$parent.find('#group-search').kendoDropDownList({
			dataTextField:'text',
			dataValueField:'value',
			dataSource:[
				{'text':'根据车主和车位分组', 'value':'1'},
				{'text':'根据车位分组', 'value':'2'},
				{'text':'根据客户分组', 'value':'3'}
			],
			change : function(e) {
				$this.findReport();
			}
		}).data('kendoDropDownList');
		Utils.createDataDictDropDownList({div:this.$parent.find("#charge-method"), parentModelKey:BASIS.CHARGE_METHOD.ROOT}, this);
		selectGroup.select(0);
        this.resetInfo();
		// this.findReport();
		this.$parent.find("#month-rent-div").height(this.$parent.height() - this.$parent.find(".search-panel").outerHeight());
	},
	/*
	 * 重置按钮
	 */
	resetInfo:function(e){
	    var date = new Date();
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
		that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
        that.sysUtils.mvvmModel.set("endTime", date.pattern("yyyy/MM/dd"));
        date.setMonth(date.getMonth() - 12);
        that.sysUtils.mvvmModel.set("beginTime", date.pattern("yyyy/MM/dd"));
	},
	findReport : function (e) {
		var $this = this;
		if (!isEmpty(e)) {
			$this = $(e.target).data('that');
		}
        var beginTime = $this.$parent.find('#beginTime').val();
        var endTime = $this.$parent.find('#endTime').val();
        var monthCount = $this.getMonthNumber(new Date(beginTime).pattern('yyyy-MM'), new Date(endTime).pattern('yyyy-MM')) + 1;
        if (monthCount > 13) {
            notification({'title':'错误', 'message':'最大选择区间为12个月！'}, 'error');
            return;
        }
		var v = $this.$parent.find('#group-search').val();
		var dataT = $this.sysUtils.getBindDocJson($this.models.bindFieldArray);
        dataT['beginTime'] = new Date(dataT['beginTime']).pattern('yyyy/MM/dd');
        dataT['endTime'] = new Date(dataT['endTime']).pattern('yyyy/MM/dd');
		$this.$parent.find('#searchYear').html(dataT['beginTime'] + '~' + dataT['endTime']);

		JsonpAjax(baseApiPath + 'charges_log/report', JSON.stringify(dataT), 'json', function (res) {
			var $table = $this.$parent.find('#tableTemp table').clone();
			$this.$parent.find(".tableDiv").empty();
			if (isEmpty(res) || res.length == 0) {
                $this.$parent.find('#allTotal').html(0);
				notification({'title':'提示', 'message':'此段范围暂无数据！'}, 'info');
				return;
			}
			if(v==1){					//全部
				$this.reportAll($this, $table, res, beginTime, endTime, monthCount);
			}else if(v==2){
				$this.reportBySpaceCode($this,$table,res,2, beginTime, endTime, monthCount);
			}else{
				$this.reportBySpaceCode($this,$table,res,1, beginTime, endTime, monthCount);
			}
		}, false);
	},
	/**
	 * 根据车位或者车主生成
	 */
	reportBySpaceCode:function($this,$table,res,fieldIndex,beginTimeStr,endTimeStr,monthCount){
        var beginTime = new Date(beginTimeStr);
        var endTime = new Date(endTimeStr);
        var titleArray = new Array();
        var custSumArry = null;
        var custSum = 0;
        var tr = '<tr id="header-tr">';
        tr += fieldIndex == 2? ('<th name="space">车位号</th>') : ('<th>车主</th>');
        tr += '<th>关联车牌</th>';
        tr += '<th>支付方式</th>';
        for (var x = 0; x < monthCount; x++) {
            titleArray.push(endTime.pattern('yyyy/M'));
            tr += "<th>"+endTime.pattern('yyyy/M')+"</th>";
            endTime = new Date(endTime.getFullYear(), endTime.getMonth()-1, 1);
        }
        tr += '<th>合计</th>';
        tr += '</tr>';
        $table.append(tr);
		this.sumArray = new Array();
        for (var x = 0; x < monthCount; x++) {
            this.sumArray.push(0);
        }
		for(var i = 0;i<res.length;i++){
			var custSum = 0;
			var tr = $("<tr></tr>");
			tr.append(fieldIndex == 2?("<td>"+res[i]['spaceCode']+"</td>"):("<td>"+res[i]['ownerName'] +"("+ res[i]['ownerCode'] +")</td>"));
            var vehicleNo = isEmpty(res[i]['vehicleNo']) ? '未绑定车牌' : res[i]['vehicleNo'];
			tr.append('<td>'+vehicleNo+'</td>');
			tr.append('<td>'+Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT, res[i]['chargeMethod'])+'</td>');
			for(var j =0;j<monthCount;j++){
			    var a = titleArray[j];
				tr.append("<td>"+res[i][a]+"</td>");
				custSum += res[i][a];
				this.sumArray[j] += res[i][a];
			}
			tr.append("<td>"+custSum+"</td>");
			$table.append(tr);
		}
		this.rowSum($this,$table,3, monthCount);
	},
	getMonthNumber : function(date1, date2) {
		var year1 = date1.substr(0, 4);
		var year2 = date2.substr(0, 4);
		var month1 = date1.substr(5, 2);
		var month2 = date2.substr(5, 2);
		var len = (year2 - year1) * 12 + (month2 - month1);
		return len;
	},
	/**
	 * 根据车位和人一起分
	 */
	reportAll:function($this, $table, res, beginTimeStr, endTimeStr,monthCount){
	    var beginTime = new Date(beginTimeStr);
	    var endTime = new Date(endTimeStr);
        var titleArray = new Array();
		var custCode = "";
		var rowSpan = 0;
		var custSumArry = null;
		var custSum = 0;
        var tr = '<tr id="header-tr">';
        tr += '<th name="cust">车主姓名</th>';
        tr += '<th name="space">车位号</th>';
        tr += '<th>关联车牌</th>';
        tr += '<th>支付方式</th>';
        for (var x = 0; x < monthCount; x++) {
            titleArray.push(endTime.pattern('yyyy/M'));
            tr += "<th>"+endTime.pattern('yyyy/M')+"</th>";
            endTime = new Date(endTime.getFullYear(), endTime.getMonth()-1, 1);
        }
        tr += '<th>合计</th>';
        tr += '</tr>';
        $table.append(tr);
		$this.sumArray = new Array();
        for (var i =0; i < monthCount; i++) {
            $this.sumArray.push(0);
        }
		for(var i = 0; i < res.length; i++){
			var tr = $("<tr></tr>");
			custSum = 0;  					    //重新计算客户小计
			rowSpan ++;
			if(custCode != res[i]['ownerCode']){			//客户编号不一致表示换人了
				tr.append("<td cust='"+res[i]['ownerCode']+"'>"+res[i]['ownerName'] +"("+ res[i]['ownerCode'] +")</td>");
				if(i != 0) {
					//换人了，给上一行添加客户小计，在算合计
					$table.find("td[cust='" + res[i - 1]['ownerCode'] + "']").attr("rowspan", rowSpan);
					var custTr = $("<tr class='small-total'><td colspan='3'> 小计：</td></tr>");
					for (var j = 0; j < monthCount; j++) {
						custTr.append("<td>" + custSumArry[j].toFixed(2) + "</td>");
						custSum += custSumArry[j];
					}
					custTr.append("<td>" + custSum.toFixed(2) + "</td>");
					$table.append(custTr);
				}
				custSum = 0;
				custCode = res[i]['ownerCode'];
				rowSpan = 1;  //重新计算跨行
				custSumArry = new Array();
                for (var x = 0; x < monthCount; x++) {
                    custSumArry.push(0);
                }
			}
			tr.append("<td>"+res[i]['spaceCode']+"</td>");
            var vehicleNo = isEmpty(res[i]['vehicleNo']) ? '未绑定车牌' : res[i]['vehicleNo'];
            tr.append('<td>'+vehicleNo+'</td>');
			tr.append("<td>"+Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT, res[i]['chargeMethod'])+"</td>");
			for(var j =0;j<monthCount;j++){
			    var a = titleArray[j];
				tr.append("<td>"+res[i][a]+"</td>");
				custSumArry[j] += res[i][a];
				$this.sumArray[j] += res[i][a];
				custSum += res[i][a];
			}
			tr.append("<td>"+custSum+"</td>");
			$table.append(tr);
			// 给最后一行加上小计
			if (res.length-1==i) {
				//换人了，给上一行添加客户小计，在算合计
				custSum = 0;
				$table.find("td[cust='" + res[i]['ownerCode'] + "']").attr("rowspan", rowSpan+1);
				var custTr = $("<tr class='small-total'><td colspan='3'> 小计：</td></tr>");
				for (var j = 0; j < monthCount; j++) {
					custTr.append("<td>" + custSumArry[j].toFixed(2) + "</td>");
					custSum += custSumArry[j];
				}
				custTr.append("<td>" + custSum.toFixed(2) + "</td>");
				$table.append(custTr);
			}
		}
		$this.rowSum($this,$table,4, monthCount);
	},
	rowSum:function($this,$table,colspan, monthCount){
		var custSum = 0;
		//加载总的合计
		var sumTr = $("<tr class='all-total'><td colspan="+colspan+"> 总计：</td></tr>");
		for(var j = 0;j<monthCount;j++){
		    var r = parseFloat($this.sumArray[j].toFixed(2));
			sumTr.append("<td>"+r+"</td>");
			custSum += r;
		}
		sumTr.append("<td>"+custSum.toFixed(2)+"</td>");
		$table.append(sumTr);
		$this.$parent.find(".tableDiv").append($table);
		$this.$parent.find('#allTotal').html(custSum.toFixed(2));
	},
	/**
	 * 打印
	 * @param e
	 */
	print:function(e){
		this.$parent.find("#month-rent-div").find("div:first").printArea({
			mode:"popup",
			popTitle:"",
			popClose:true,
			popHt:600,
			popWd:1000
		});
	},
	/**
	 * 导出Excel文件
	 */
	exportExcel:function(e){
		var $this = this;
		if (!isEmpty(e)) {
			$this = $(e.target).data('that');
		}
		var beginTime = $this.$parent.find('#beginTime').val();
		var endTime = $this.$parent.find('#endTime').val();
		var monthCount = $this.getMonthNumber(new Date(beginTime).pattern('yyyy-MM'), new Date(endTime).pattern('yyyy-MM')) + 1;
		if (monthCount > 13) {
			notification({'title':'错误', 'message':'最大选择区间为12个月！'}, 'error');
			return;
		}
		var dataT = $this.sysUtils.getBindDocJson($this.models.bindFieldArray);
		dataT['beginTime'] = new Date(dataT['beginTime']).pattern('yyyy/MM/dd');
		dataT['endTime'] = new Date(dataT['endTime']).pattern('yyyy/MM/dd');

		window.open(baseApiPath+'charges_log/report/excel?jsonData='+encodeURI(JSON.stringify(dataT)));
	}
};